<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="shop_id" label="绑定店铺id">
        <uni-easyinput v-model="formData.shop_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="title" label="店铺名称" required>
        <uni-easyinput placeholder="店铺名称最少为2个汉字，最多为30个汉字，不要使用特殊字符" v-model="formData.title" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="categories" label="店铺分类" required>
        <uni-data-picker v-model="formData.categories" collection="opendb-mall-categories" orderby="sort asc" field="_id as value, name as text"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="delivery_timeliness" label="配送时效" required>
        <picker @change="pickerChange($event, 'delivery_timeliness')" :range="formOptions.delivery_timeliness_data" :value="formOptions.delivery_timeliness_index">
          <view>{{formOptions.delivery_timeliness_data[formOptions.delivery_timeliness_index] || "请选择..."}}</view>
        </picker>
      </uni-forms-item>
      <uni-forms-item name="score" label="店铺评分">
        <picker @change="pickerChange($event, 'score')" :range="formOptions.score_data" :value="formOptions.score_index">
          <view>{{formOptions.score_data[formOptions.score_index] || "请选择..."}}</view>
        </picker>
      </uni-forms-item>
      <uni-forms-item name="image" label="商品列表，最多4个">
        <uni-data-checkbox :multiple="true" v-model="formData.image"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="monthly_sales" label="月销售量">
        <uni-easyinput placeholder="店铺月销售量，按30天累计计算" type="number" v-model="formData.monthly_sales"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="total_sales" label="总销售量">
        <uni-easyinput placeholder="店铺总销售量，从开店一直累计计算" type="number" v-model="formData.total_sales"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="region" label="店铺地址" required>
        <uni-data-picker self-field="code" parent-field="parent_code" v-model="formData.region" collection="opendb-city-china" orderby="value asc" field="code as value,name as text,eq(type,2) as isleaf"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="address" label="详细地址" required>
        <uni-easyinput placeholder="店铺详细地址，精确到门牌号" v-model="formData.address" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="poiname" label="地标名称">
        <uni-easyinput placeholder="由地图选择提供" v-model="formData.poiname"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="start_business_hours1" label="开始营业时间段1" required>
        <picker mode="time" start="00:00" end="23:59" placeholder="店铺开始营业时间" @change="binddata('start_business_hours1', $event.detail.value)" v-model="formData.start_business_hours1">
          <view>{{formData.start_business_hours1 || '店铺开始营业时间'}}</view>
        </picker>
      </uni-forms-item>
      <uni-forms-item name="end_business_hours1" label="结束营业时间段1" required>
        <picker mode="time" start="00:00" end="23:59" placeholder="店铺结束营业时间" @change="binddata('end_business_hours1', $event.detail.value)" v-model="formData.end_business_hours1">
          <view>{{formData.end_business_hours1 || '店铺结束营业时间'}}</view>
        </picker>
      </uni-forms-item>
      <uni-forms-item name="start_business_hours2" label="开始营业时间段2">
        <picker mode="time" start="00:00" end="23:59" placeholder="店铺开始营业时间" @change="binddata('start_business_hours2', $event.detail.value)" v-model="formData.start_business_hours2">
          <view>{{formData.start_business_hours2 || '店铺开始营业时间'}}</view>
        </picker>
      </uni-forms-item>
      <uni-forms-item name="end_business_hours2" label="结束营业时间段2">
        <picker mode="time" start="00:00" end="23:59" placeholder="店铺结束营业时间" @change="binddata('end_business_hours2', $event.detail.value)" v-model="formData.end_business_hours2">
          <view>{{formData.end_business_hours2 || '店铺结束营业时间'}}</view>
        </picker>
      </uni-forms-item>
      <uni-forms-item name="photo" label="店铺照片" required>
        <uni-data-checkbox :multiple="true" v-model="formData.photo"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="tel" label="手机号码">
        <uni-easyinput v-model="formData.tel" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="intro" label="简介" required>
        <uni-easyinput type="textarea" v-model="formData.intro" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="start_delivery_price" label="起送费">
        <uni-easyinput placeholder="客户购买需满足该价格才能配送" type="number" v-model="formData.start_delivery_price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="delivery_price" label="配送费">
        <uni-easyinput placeholder="添加商品时会默认采用此配送费" type="number" v-model="formData.delivery_price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="pack_price" label="打包费">
        <uni-easyinput placeholder="添加商品时会默认采用此打包费" type="number" v-model="formData.pack_price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="auto_order" label="是否自动接单">
        <switch @change="binddata('auto_order', $event.detail.value)" :checked="formData.auto_order"></switch>
      </uni-forms-item>
      <uni-forms-item name="dining_out_time" label="出餐时间">
        <uni-easyinput type="number" v-model="formData.dining_out_time"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="money" label="账户总余额">
        <uni-easyinput placeholder="账户总余额" type="number" v-model="formData.money"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="is_book" label="是否可预订">
        <switch @change="binddata('is_book', $event.detail.value)" :checked="formData.is_book"></switch>
      </uni-forms-item>
      <uni-forms-item name="is_take_away" label="是否可外卖">
        <switch @change="binddata('is_take_away', $event.detail.value)" :checked="formData.is_take_away"></switch>
      </uni-forms-item>
      <uni-forms-item name="create_uid" label="创建人">
        <uni-easyinput v-model="formData.create_uid"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="keywords" label="关键词">
        <uni-data-checkbox :multiple="true" v-model="formData.keywords"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="preferential" label="满减优惠">
        <uni-data-checkbox :multiple="true" v-model="formData.preferential"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="page_view" label="浏览量">
        <uni-easyinput placeholder="店铺浏览量，每次访问自动加1" type="number" v-model="formData.page_view"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="evaluate" label="评价量">
        <uni-easyinput placeholder="店铺评价数量，每次自动加1" type="number" v-model="formData.evaluate"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="goods" label="商品数量">
        <uni-easyinput placeholder="商品数量，累计计算商品表" type="number" v-model="formData.goods"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="disabled_status" label="店铺状态">
        <switch @change="binddata('disabled_status', $event.detail.value)" :checked="formData.disabled_status"></switch>
      </uni-forms-item>
      <uni-forms-item name="business_status" label="经营状态">
        <switch @change="binddata('business_status', $event.detail.value)" :checked="formData.business_status"></switch>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../../js_sdk/validator/shop_examine.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'shop_examine';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  function numberRange(start, end) {
    return Array.from(new Array(end + 1).keys()).slice(start);
  }

  export default {
    data() {
      let formData = {
        "shop_id": "",
        "title": "",
        "categories": "",
        "delivery_timeliness": 45,
        "score": 5,
        "image": [],
        "monthly_sales": 0,
        "total_sales": 0,
        "region": "",
        "address": "",
        "poiname": "",
        "start_business_hours1": "",
        "end_business_hours1": "",
        "start_business_hours2": "",
        "end_business_hours2": "",
        "photo": [],
        "tel": "",
        "intro": "",
        "start_delivery_price": 0,
        "delivery_price": 0,
        "pack_price": 0,
        "auto_order": true,
        "dining_out_time": 15,
        "money": 0,
        "is_book": true,
        "is_take_away": true,
        "create_uid": "",
        "keywords": [],
        "preferential": [],
        "page_view": 0,
        "evaluate": 0,
        "goods": 0,
        "disabled_status": true,
        "business_status": true
      }
      return {
        formData,
        formOptions: {
          "delivery_timeliness_data": numberRange(10, 100),
          "delivery_timeliness_index": 45,
          "score_data": numberRange(0, 5),
          "score_index": 5
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      pickerChange(e, name) {
        this.formOptions[name + '_index'] = e.detail.value;
        this.formData[name] = this.formOptions[name + '_data'][e.detail.value];
        this.binddata(name, this.formData[name]);
      },
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("shop_id,title,categories,delivery_timeliness,score,image,monthly_sales,total_sales,region,address,poiname,start_business_hours1,end_business_hours1,start_business_hours2,end_business_hours2,photo,tel,intro,start_delivery_price,delivery_price,pack_price,auto_order,dining_out_time,money,is_book,is_take_away,create_uid,keywords,preferential,page_view,evaluate,goods,disabled_status,business_status").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            for (let key in this.formOptions) {
              let pickerIndex = key.lastIndexOf("_index")
              if (pickerIndex > -1) {
                let fieldName = key.substring(0, pickerIndex)
                let fieldData = this.formOptions[fieldName + "_data"];
                if (data[fieldName] && fieldData && fieldData.indexOf(data[fieldName]) > -1) {
                  this.formOptions[fieldName + "_index"] = fieldData.indexOf(data[fieldName])
                }
              }
            }
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
